Assignment Operator
The assignment operator (a = b) initializes or updates the value of a with the value of b:
1 | let b = 10 |
Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value.
1 | if x = y { |
Arithmetic Operators
Unlike the arithmetic operators in C and Objective-C, the Swift arithmetic operators do not allow values to overflow by default.
1 | 1 + 2 // equals 3 |
Compound Assignment Operators
1 | var a = 1 |
Comparison Operators
- Each of the comparison operators returns a Bool value to indicate whether or not the statement is true
- Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance
1 | 1 == 1 // true because 1 is equal to 1 |
Tuple comparison
- The Swift standard library includes tuple comparison operators for tuples with fewer than seven elements. To compare tuples with seven or more elements, you must implement the comparison operators yourself.
- Tuples are compared from left to right, one value at a time, until the comparison finds two values that aren’t equal.
1 | (1, "zebra") < (2, "apple") |
Ternary Conditional Operator
The ternary conditional operator is shorthand for the code below:
1 | if question { |
question ? answer1 : answer2
1 | let contentHeight = 40 |
Nil-Coalescing Operator
The nil-coalescing operator is shorthand for the code below:
1 | a != nil ? a! : b |
The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil
1 | let defaultColorName = "red" |
Range Operators
Closed Range Operator
The closed range operator (a…b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.
1 | for index in 1...5 { |
Half-Open Range Operator
The half-open range operator (a..<b) defines a range that runs from a to b, but does not include b.
1 | let names = ["Anna", "Alex", "Brian", "Jack"] |
Logical Operators
The logical NOT operator (!a)
1 | let allowedEntry = false |
The logical AND operator (a && b) creates logical expressions where both values must be true for the overall expression to also be true.
1 | let enteredDoorCode = true |
The logical OR operator (a || b)
1 | let hasDoorKey = false |
The Swift logical operators && and || are left-associative, meaning that compound expressions with multiple logical operators evaluate the leftmost subexpression first.
1 | if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword { |
Explicit Parentheses
1 | if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword { |